package com.zaker.touchtv.modules.live;

import android.content.Context;
import android.support.annotation.NonNull;
import android.util.Log;

import com.github.faucamp.simplertmp.RtmpHandler;
import com.zaker.rtmp.RtmpPublisher;
import com.zaker.touchtv.modules.polling.PollTask;
import com.zaker.touchtv.utils.Constants;

import net.ossrs.yasea.SrsMp4Muxer;
import net.ossrs.yasea.SrsNetworkHandler;
import net.ossrs.yasea.SrsPublisher;
import net.ossrs.yasea.SrsRecordHandler;

import static com.zaker.touchtv.utils.Constants.LOG_TAG;

public class LiveMainController implements ILivePresenter ,RtmpHandler.RtmpListener,
    SrsRecordHandler.SrsRecordListener, SrsNetworkHandler.SrsNetworkListener{

  private final LiveMainLayout mLiveMainLayout;
  private final SrsPublisher mPublisher;

  private final PollTask mPollTask;
  private final LiveHeartbeatRunnable mHeartbeatRunnable;

  private boolean alreadyStart = false;

  public LiveMainController(final LiveActivity liveActivity,
                            @NonNull LiveMainLayout liveMainLayout,
                            String liveId) {
    mLiveMainLayout = liveMainLayout;
    mPublisher = new SrsPublisher();
    mPublisher.setSurfaceView(mLiveMainLayout.mLivePlaySurfaceView);

    mPublisher.setPublishEventHandler(new RtmpPublisher.EventHandler() {
      String mNotifyMsg;

      @Override
      public void onRtmpConnecting(String msg) {
        Log.i(LOG_TAG, " RtmpPublisher.EventHandler onRtmpConnecting msg : " + msg);
        mNotifyMsg = msg;
//        liveActivity.runOnUiThread(new Runnable() {
//          @Override
//          public void run() {
//            liveActivity.showProgressDialog();
//          }
//        });
      }

      @Override
      public void onRtmpConnected(String msg) {
        Log.i(LOG_TAG, " RtmpPublisher.EventHandler onRtmpConnected msg : " + msg);
        ping(Constants.LIVE_STARTING_STATE);
        mNotifyMsg = msg;
        alreadyStart = true;
        liveActivity.runOnUiThread(new Runnable() {
          @Override
          public void run() {
            liveActivity.dismissProgressDialog();
          }
        });
      }

      @Override
      public void onRtmpVideoStreaming(String msg) {
        //Log.i(LOG_TAG," RtmpPublisher.EventHandler onRtmpVideoStreaming msg : " + msg);
      }

      @Override
      public void onRtmpAudioStreaming(String msg) {
        // Log.i(LOG_TAG," RtmpPublisher.EventHandler onRtmpAudioStreaming msg : " + msg);
      }

      @Override
      public void onRtmpStopped(String msg) {
        Log.i(LOG_TAG, " RtmpPublisher.EventHandler onRtmpStopped msg : " + msg);
        mNotifyMsg = msg;
        ping(Constants.LIVE_PAUSE_STATE);
      }

      @Override
      public void onRtmpDisconnected(String msg) {
        Log.i(LOG_TAG, " RtmpPublisher.EventHandler onRtmpDisconnected msg : " + msg);
        mNotifyMsg = msg;
        ping(Constants.LIVE_DESTROY_STATE);
      }

      @Override
      public void onRtmpOutputFps(final double fps) {
        Log.i(LOG_TAG, " RtmpPublisher.EventHandler onRtmpOutputFps "
            + String.format("Output Fps: %f", fps));
      }
    });

    mPublisher.setRecordEventHandler(new SrsMp4Muxer.EventHandler() {
      @Override
      public void onRecordPause(String msg) {
        Log.i(LOG_TAG, " SrsMp4Muxer.EventHandler onRecordPause msg : " + msg);
      }

      @Override
      public void onRecordResume(String msg) {
        Log.i(LOG_TAG, " SrsMp4Muxer.EventHandler onRecordResume msg : " + msg);
      }

      @Override
      public void onRecordStarted(String msg) {
        Log.i(LOG_TAG, " SrsMp4Muxer.EventHandler onRecordStarted msg : " + msg);
      }

      @Override
      public void onRecordFinished(String msg) {
        Log.i(LOG_TAG, " SrsMp4Muxer.EventHandler onRecordFinished msg : " + msg);
      }
    });

    final Context appContext = liveMainLayout.getContext().getApplicationContext();
    mPollTask = new PollTask();
    mHeartbeatRunnable = new LiveHeartbeatRunnable(appContext, liveId);
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
      @Override
      public void uncaughtException(Thread thread, Throwable ex) {
        mPublisher.stopPublish();
        mPublisher.stopRecord();

        Log.i(LOG_TAG, "UncaughtExceptionHandler Throwable: " + ex.getMessage());
      }
    });
  }

  @Override
  public boolean isStart() {
    return alreadyStart;
  }

  private void ping(@Constants.LiveState int liveState) {
    mHeartbeatRunnable.setLiveState(liveState);
    mPollTask.executePollTask(mHeartbeatRunnable);
  }

  @Override
  public void onStartLive(String rtmpSite) {

//    int width = mLiveMainLayout.mLivePlaySurfaceView.getWidth();
//    int height = mLiveMainLayout.mLivePlaySurfaceView.getHeight();
//    mPublisher.setPreviewResolution(width, height);
//    mPublisher.setOutputResolution(width, height);
//    mPublisher.setVideoSmoothMode();

    mPublisher.setPreviewResolution(640, 480);
    mPublisher.setOutputResolution(384, 640);
    mPublisher.setVideoHDMode();

    mPublisher.startPublish(rtmpSite);
  }

  @Override
  public void onPauseLive() {
    ping(Constants.LIVE_PAUSE_STATE);
    mPublisher.pauseRecord();
  }

  @Override
  public void onResumeLive() {
    mPublisher.resumeRecord();
  }

  @Override
  public void onStopLive() {
    ping(Constants.LIVE_DESTROY_STATE);
    mPublisher.stopPublish();
    mPublisher.stopRecord();
    mPublisher.setPublishEventHandler(null);
    mPublisher.setRecordEventHandler(null);
    mPollTask.destroyPollTask();
  }

  @Override
  public void switchCamera() {
    if (mPublisher != null && alreadyStart) {
      mPublisher.switchCameraFace();
    }
  }
}
